package com.baibei.ebec.user.login;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.basic.module.validator.PhoneValidator;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.model.UserInfo;
import com.baibei.model.event.LoginEvent;
import com.baibei.sdk.ApiDefaultObserver;
import com.blankj.utilcode.utils.LogUtils;
import com.rae.swift.session.SessionManager;

import org.greenrobot.eventbus.EventBus;

/**
 * 登录逻辑
 * Created by ChenRui on 2017/4/28 0028 17:05.
 */
public class LoginPresenterImpl extends BasicPresenterImpl<LoginContract.View> implements LoginContract.Presenter {

    IUserApi mUserApi;
    private PhoneValidator mPhoneValidator = new PhoneValidator();

    public LoginPresenterImpl(Context context, LoginContract.View view) {
        super(context, view);
        mUserApi = ApiFactory.getInstance().getUserApi();
    }

    @Override
    public void login() {
        final String mobile = mView.getMobile();
        final String password = mView.getPassword();
        final String invitedCode = mView.getInvitationCode();
        final String imei = mView.getImei();

        if (TextUtils.isEmpty(mobile)) {
            mView.onLoginFailed("请输入手机号码");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            mView.onLoginFailed("请输入密码");
            return;
        }
        if (!isMobileNum(mobile) ) {
            mView.onLoginFailed("请输入正确的手机号码");
            return;
        }
//        if (TextUtils.isEmpty(invitedCode)) {
//            mView.onLoginFailed("测试环境中的邀请码不允许为空");
//            return;
//        }


        performLogin(mobile, password, invitedCode, imei);
    }

    public boolean isMobileNum(String mobiles) {
        String telRegex = "[1]\\d{10}";
        return TextUtils.isEmpty(mobiles)?false:mobiles.matches(telRegex);
    }

    @Override
    public void cancel() {
        cancelRequest();
    }


    /**
     * 执行登录
     *
     * @param mobile   手机号
     * @param password 密码
     */
    protected void performLogin(String mobile, String password, String invitationCode,String imei) {
        createObservable(mUserApi.signIn(mobile, password, invitationCode,imei)).subscribe(new ApiDefaultObserver<UserInfo>() {
            @Override
            protected void onError(String msg) {
                mView.onLoginFailed(msg);
            }

            @Override
            protected void accept(UserInfo userInfo) {
                // 登录成功
                SessionManager.getDefault().setUser(userInfo);
                LogUtils.i("api", "登录信息：" + SessionManager.getDefault().getUserToken());
                mView.onLoginSuccess();

                // 发送事件
                LoginEvent event = new LoginEvent();
                event.setLogin(true);
                EventBus.getDefault().post(event);
            }
        });
    }
}
